<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="660"
    :minHeight="300">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { getMenuTree,saveOrUpdateMenu } from '@/api/system/menu';
import { useForm } from '@/components/Form';
import { BasicModal } from '@/components/Modal';
import { useModalInner } from '@/components/Modal/src/hooks/useModal';
import { ModalMethods } from '@/components/Modal/src/typing';
import { computed, ref, unref } from 'vue';
import { menuFormSchema } from './menu.data';
import { Recordable } from '/#/global';



const emit = defineEmits<{
  (e: 'register', modalMethod: ModalMethods, uuid: string): void,
  (e: 'success', o: Recordable): void
}>()

const isUpdate = ref(true)
const rowId = ref('');


const [registerForm, { setFieldsValue, resetFields, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: menuFormSchema,
  componentMinWidth: 100

})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ loading: true });
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  const menuTree = await getMenuTree()

  updateSchema([
    {
      field: 'pid',
      componentProps: {
        data: menuTree
      }
    },])

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
    });
  } else {
    rowId.value = ''
  }

  setModalProps({ loading: false });
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));


async function handleSubmit() {
  try {
    // callback?: (isValid: boolean, invalidFields?: ValidateFieldsError)
    const values = await validate();

    console.log(values)
    // // 这里来请求api

    await saveOrUpdateMenu({ ...values, id: rowId.value })

    setModalProps({ confirmLoading: true })
    closeModal();
    emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value, state: values['enabled'] === '1' } });

  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>